<template>
  <Layout style="height: 100%" class="main">
    <Header>
      <Menu mode="horizontal" theme="dark" active-name="1">
        <div class="logo-v3">
          <img :src="logoTime" class="hd-img-responsive"/>
        </div>
        <div class="back-v3">
          <Dropdown style="margin-left: 20px" trigger="click" transfer @on-click="openPage">
            <Button type="primary" style="font-size: 16px;color: white;font-weight: bold;background: #235CA7;line-height: 17px;border:0px solid #235CA7">
              <Icon type="md-menu" />
              {{ menuName }}
            </Button>
            <DropdownMenu slot="list" class="ivu-dropdown-menu" >
              <DropdownItem v-for="(item,index) in minZhengMenus" :key="index" :name="item.name+'='+item.path">
                <span style="font-size: 14px">{{item.name}}</span>
              </DropdownItem>
            </DropdownMenu>
          </Dropdown>
          <div class="login-info">
            <div class="user-info">
              <span>{{personData.name}}</span>
              <span> [{{personData.company_name}}] </span>
            </div>
<!--&lt;!&ndash;            <div v-for="(item,index) in minZhengMenus" :key="index" style="margin-left: 20px;font-size: 15px">&ndash;&gt;-->
<!--&lt;!&ndash;              <span @click="openPage(item.path)">{{item.name}}</span>&ndash;&gt;-->
<!--&lt;!&ndash;            </div>&ndash;&gt;-->
          </div>
          <div class="login-btn">
            <div class="logout-btn logout-btn-item" @click="deviceBinding2()">
              <Tooltip content="客服服务" placement="bottom">
                <Button icon="iconfont icon-kefu" type="default" shape="circle" ghost></Button>
              </Tooltip>
              <!-- :17642057151、17640241887、13324056283 -->
            </div>
            <div class="logout-btn logout-btn-item" @click="passwordInfo.show=true">
              <Tooltip content="修改密码" placement="bottom">
                <Button icon="iconfont icon-xiugaimima" type="dashed" shape="circle" ghost></Button>
              </Tooltip>
              <!-- <Icon type="md-create"/>
              修改密码 -->
            </div>
            <div class="logout-btn logout-btn-item" @click="logout">
              <Tooltip content="注销" placement="bottom">
                <Button icon="iconfont icon-zhuxiao" type="error" shape="circle" ghost></Button>
              </Tooltip>
              <!-- <Icon type="md-log-out"/>
              注销 -->
            </div>
          </div>
        </div>
        <Modal v-model="modalDevice1" title="下载中心" width="700"
               style="position:relative;">
          <div style="line-height:25px">
            <div style="font-size: 14px;color: #2E2D3C;font-weight: bold;margin-bottom: 20px">设备驱动下载</div>
            <div >捷宇高拍仪
            </div>
            <div>良田高拍仪
              <a style="margin-right: 50px;margin-left: 50px" href="https://pan.baidu.com/s/1Sp7a4Mw3BU-4stZM-zRJOA" target="_blank">https://pan.baidu.com/s/1Sp7a4Mw3BU-4stZM-zRJOA</a>
              <span>提取码：qfsi</span></div>
            <div>紫图高拍仪
              <a style="margin-right: 35px;margin-left: 50px" href="https://pan.baidu.com/s/1CM7b4_EiRI33HkuByBjuCw" target="_blank">https://pan.baidu.com/s/1CM7b4_EiRI33HkuByBjuCw</a>
              <span>提取码：6hso</span></div>
            <div>德意拍高拍仪
              <a style="margin-right: 60px;margin-left: 40px" href="https://pan.baidu.com/s/1RMOLv2xXtwqh8pCFfFSrtA" target="_blank">https://pan.baidu.com/s/1RMOLv2xXtwqh8pCFfFSrtA</a>
              <span>提取码：8mzs</span>
            </div>
            <div>维山高拍仪
              <a style="margin-right: 60px;margin-left: 40px" href="https://pan.baidu.com/s/1ee3QkVNVP4xJskVsOgnvFA" target="_blank">https://pan.baidu.com/s/1ee3QkVNVP4xJskVsOgnvFA</a>
              <span>提取码：saw4</span>
            </div>
            <div>点易拍高拍仪</div>
          </div>
          <Divider/>
          <div style="line-height:25px">
            <div style="font-size: 14px;color: #2E2D3C;font-weight: bold;margin-bottom: 20px">培训视频下载</div>
            <div>视频
              <a style="margin-right: 50px;margin-left: 90px" href="https://pan.baidu.com/s/1vSMpSicWSTuLqVa5i2173g" target="_blank">https://pan.baidu.com/s/1vSMpSicWSTuLqVa5i2173g</a>
              <span>提取码：lj2w</span>
            </div>
          </div>
        </Modal>
        <Modal v-model="modalDevice" title="选择该社区使用的设备" width="500" cancel-text="关闭"
               @on-ok="saveDevice()" @on-cancel="modalDevice = false" ok-text="确定"
               style="position:relative;">
          <div style="display: table-caption; line-height:25px">
            <RadioGroup v-model="highMeter1">
              <Radio label="JieYuDevice">
                <span>捷宇高拍仪</span>
              </Radio>
              <Radio label="LiangTianDevice">
                <span>良田高拍仪</span>
              </Radio>
              <Radio label="ZiTuDevice">
                <span>紫图高拍仪</span>
              </Radio>
              <Radio label="DeYiPaiDevice">
                <span>德意拍高拍仪</span>
              </Radio>
              <Radio label="WeiShanDevice">
                <span>维山高拍仪</span>
              </Radio>
              <Radio label="DianYiPaiDevice">
                <span>点易拍高拍仪</span>
              </Radio>
            </RadioGroup>
          </div>
        </Modal>
        <Modal v-model="modalDevice2" width="900"
               style="position:relative;">
          <div style="padding:50px" v-html="modalDevice2html">
          </div>
          <Divider/>
        </Modal>
        <Modal v-model="display_model1_obj1.modal1" width="900" :mask-closable="false">
          <div style="padding:50px" v-html="display_model1_obj1.html">
          </div>
          <div slot="footer">
            <Button type="primary" :disabled="!disabledCodeBtn" @click="savelogea">{{time}}确认</Button>
          </div>
        </Modal>
        <Modal v-model="modalQr" title="二维码" width="500" cancel-text="关闭"
               @on-ok="modalQr = false" @on-cancel="modalQr = false" ok-text="确定"
               style="position:relative;">
          <div id="qrcode" ref="qrcode" style="margin-left: 18%"></div>
          <div style="text-align: center;margin-top: 10px;font-size: 1rem;">扫描二维码绑定用户信息</div>
        </Modal>
      </Menu>
    </Header>
    <Layout>
      <Modal v-model="display_model1_obj.modal1" :title="display_model1_obj.text" width="900">
        <div id="printMe">
          <Form label-position="right" :label-width="100">
            <Row>
              <Col span="24" class="ivu-form-item-content" style="text-align: center">
                <embed width="800" v-show="display_model1_obj.modal1" height="600"
                       :src="display_model1_obj.filepath"></embed>
              </Col>
            </Row>
          </Form>
        </div>
        <div slot="footer">
          <Button type="error" size="large" @click="display_model1_obj.modal1=false">关闭</Button>
        </div>
      </Modal>
      <Modal v-model="passwordInfo.show" title="修改密码" width="600" :closable="false" :mask-closable="false">
        <Form label-position="right" :label-width="100" ref="passwordInfo" :model="passwordInfo"
              :rules="ruleInline">
          <FormItem prop="oldpassword" label="旧密码：" class="set-password-input">
            <Input type="password" v-model="passwordInfo.oldpassword"></Input>
          </FormItem>
          <FormItem prop="newpassword" label="新密码：" class="set-password-input">
            <Input type="password" v-model="passwordInfo.newpassword"></Input>
          </FormItem>
          <FormItem prop="repassword" label="确认密码：" class="set-password-input">
            <Input type="password" v-model="passwordInfo.repassword"></Input>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="success" size="large" @click="setPassWord('passwordInfo')">确认</Button>
          <Button type="error" size="large" @click="closePassWord('passwordInfo')">关闭</Button>
        </div>
      </Modal>
      <Layout class="content-layout-v3" :style="{overflow: 'hidden',maxHeight: maxH+'px',overflowY:'scroll'}">
<!--        <div class="tag-nav-wrapper">-->
<!--          <Tabs :animated="false" @on-click="openPage" value="name1">-->
<!--            <TabPane v-for="(item,index) in minZhengMenus" :key="index" :label="item.name" :name="item.path" :icon="item.icon"></TabPane>-->
<!--          </Tabs>-->
<!--        </div>-->
        <Content :style="{padding: '15px', background: '#fff'}">
          <keep-alive :include="cacheList">
            <router-view/>
          </keep-alive>
          <!-- <router-view></router-view> -->
        </Content>
      </Layout>
    </Layout>
  </Layout>
</template>

<script>
import './index.less'
import logoTime from '@/assets/images/backImg.png'
import { mapMutations, mapActions, mapGetters } from 'vuex'
import { updatePwd } from '@/api/user'
import { mzMenulist, findHtmlList, getHtml1, savelog } from '@/api/eventlist'
import ThreeMenu from './three-menu'
import device from '@/view/demo/device'
import { clearInterval } from 'timers'
import QRCode from 'qrcodejs2'
import { updateUserGPY } from '@/api/common'
import YiqingMenu from '@/view/xian-page/indexv3/yiqing-menu/yiqing-menu'
import TagsNav from '@/components/main/components/tags-nav'
import { getNewTagList, routeEqual, getMenuByRouter, localSave, localClear } from '@/libs/util'
import { getRouterReq } from '@/api/routers'
import routers from '@/router/routers'

export default {
  name: 'indexv3',
  components: {
    YiqingMenu,
    ThreeMenu,
    device,
    TagsNav
    // TransitionNotice
    // scrollAd
  },
  data () {
    const validatePassCheck = (rule, value, callback) => {
      if (value !== this.passwordInfo.newpassword) {
        callback(new Error('确认密码与新密码不相同'))
      } else {
        callback()
      }
    }
    return {
      menuName: '',
      device_code: '', // 高拍仪参数
      highMeter1: '', // 高拍仪
      highMeter2: '', // 高拍仪
      highMeter3: '', // 高拍仪
      type: '',
      shuju: [],
      codeUrl: '',
      company_codes: '',
      loginCompanyType: '1', // 登录账号类型 1城市 2农村
      loginNames: '',
      modalDevice: false,
      modalDevice1: false,
      modalDevice2: false,
      modalDevice3: true,
      disabledCodeBtn: false,
      htmllist: [],
      time: '',
      display_model1_obj1: { modal1: false, filepath: '', html: '' },
      modalDevice2html: '',
      modalQr: false,
      timerInterval: null,
      collapsed: false,
      reloadItem: false,
      logoTime,
      totalItemNum: 0,
      totalBMNum: 0,
      treeDataList: [],
      searchName: '',
      personData: {},
      routeList: [],
      passwordInfo: { show: false },
      display_model1_obj: { modal1: false, filepath: '' },
      maxH: `${document.documentElement.clientHeight}` - 166,
      ruleInline: {
        oldpassword: [
          { required: true, message: '请填写旧密码', trigger: 'blur' }
        ],
        newpassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        repassword: [
          { required: true, message: '请填写确认密码', trigger: 'blur' },
          { type: 'string', min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
          { validator: validatePassCheck, trigger: 'blur' }
        ]
      },
      yiQingMenus: [],
      minZhengMenus: [],
      adList: [
        // { content: '全科社工们，系统喊你快来试用', ink: 'xx.com' }
      ],
      location_url: '',
      textArr: [],
      number: 0,
      tempTagNavList: []
    }
  },
  computed: {
    text () {
      return {
        id: this.number,
        val: this.textArr[this.number]
      }
    },
    ...mapGetters([
      'errorCount'
    ]),
    tagNavList () {
      return this.$store.state.app.tagNavList
    },
    tagRouter () {
      return this.$store.state.app.tagRouter
    },
    userAvator () {
      return this.$store.state.user.avatorImgPath
    },
    cacheList () {
      const list = ['ParentView', ...this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []]
      return list
    },
    local () {
      return this.$store.state.app.local
    },
    hasReadErrorPage () {
      return this.$store.state.app.hasReadErrorPage
    },
    unreadCount () {
      return this.$store.state.user.unreadCount
    }
  },
  methods: {
    ClickRouter () {

    },
    hreftwo () {
      this.$router.push({ path: '/message' })
    },
    startMove () {
      // eslint-disable-next-line
        let timer = setTimeout(() => {
        if (this.number === this.textArr.length) {
          this.number = 0
        } else {
          this.number += 1
        }
        this.startMove()
      }, 2500) // 滚动不需要停顿则将2000改成动画持续时间
    },
    ...mapActions([
      'handleLogOut'
    ]),
    getNetworkIp () {
      let needHost = '' // 打开的host
      try {
        // 获得网络接口列表
        let network = os.networkInterfaces()
        for (let dev in network) {
          let iface = network[dev]
          for (let i = 0; i < iface.length; i++) {
            let alias = iface[i]
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
              needHost = alias.address
            }
          }
        }
      } catch (e) {
        needHost = 'localhost'
      }
      return needHost
    },
    mzMenulist () {
      // console.log(location.href)
      // let a = this.getNetworkIp()
      // console.log('aaaaaaaa', a)
      let menu_id = '3c649d25-f33c-11ea-88c8-0242ac11000f'
      mzMenulist(menu_id).then(ret => {
        if (ret.data.errcode === 0) {
          this.minZhengMenus = ret.data.data.list[0].list
          this.minZhengMenus.forEach(item => {
            if (item.path === this.$route.path) {
              this.menuName = item.name
            }
          })
          // this.menuName = this.minZhengMenus[0].name
          // this.minZhengMenus.unshift(
          //   { name: '首页',
          //     type_id: 20001,
          //     icon: 'md-home',
          //     path: '/mainv3' }
          // )
        }
      })
    },
    logout () {
      this.handleLogOut().then(() => {
        clearInterval(this.timerInterval)
        localClear()
        // this.token = localStorage.getItem('token')
        // localStorage.setItem('token', this.token)
        // let a = this.getNetworkIp()
        // console.log('aaaaaaaa', a)
        if (location.href.indexOf('qstb.mzj.shenyang.gov.cn') !== -1) {
          window.open('http://qstb.mzj.shenyang.gov.cn/#/login')
        } else { // 生产环境
          this.$router.push({ name: 'login' })
        }
        // if (location.href.startsWith('http://localhost')) {
        //   this.$router.push({
        //     name: 'login'
        //   })
        // } else {
        //   window.location.href = 'http://qstb.mzj.shenyang.gov.cn/#/login'
        // }
      })
    },
    closePassWord (name) {
      this.passwordInfo.show = false
      this.$refs[name].resetFields()
    },
    setPassWord (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          updatePwd(this.passwordInfo).then(res => {
            if (res.data.data) {
              this.$Notice.success({ title: '修改成功', desc: '修改密码后需要重新登录' })
              this.passwordInfo.show = false
              this.logout()
            } else {
              this.$Notice.error({ title: '修改失败', desc: res.data.errmsg })
            }
          })
        } else {
          this.$Notice.error({ title: '信息错误', desc: '密码修改信息错误，请重新填写' })
        }
      })
    },
    viewProcess (item) {
      if (item.file_url) {
        this.display_model1_obj.text = item.type_name
        this.display_model1_obj.modal1 = true
        this.display_model1_obj.filepath = item.file_url
      } else {
        this.$Notice.error({ title: '无文件', desc: '当前事项无PDF说明文档' })
      }
    },
    openPage (e) {
      console.log('!!!', e)
      // console.log('!!!!!', e)
      if (e) {
        let a = e.split('=')
        this.menuName = a[0]
        this.$router.push({ path: a[1] })
      } else {
        this.$Notice.error({ title: '无文件', desc: '等待添加路径' })
      }
    },
    searchList1 () {
      if (!this.searchName) {
        this.searchList()
      }
    },
    searchList () {
      this.reloadItem = true
      this.treeDataList.forEach(e1 => {
        e1.hidden = true
        if (e1.children) {
          let curNum1 = 0
          e1.children.forEach(e2 => {
            if (e2.children) {
              let curNum2 = 0
              e2.children.forEach(e3 => {
                e3.hidden = true
                if (e3.type_name.indexOf(this.searchName) >= 0) {
                  e3.hidden = false
                  curNum2++
                  curNum1++
                }
              })
              e2.hidden = true
              if (curNum2 > 0) {
                e2.count = curNum2
                e2.hidden = false
              }
            } else {
              e2.hidden = true
              if (e2.type_name.indexOf(this.searchName) >= 0) {
                e2.hidden = false
                curNum1++
              }
            }
          })
          if (curNum1 > 0) {
            e1.count = curNum1
            e1.hidden = false
          }
        } else {
          if (!this.searchName) {
            e1.hidden = false
          }
        }
      })
      this.$nextTick(() => {
        this.reloadItem = false
      })
    },
    getCode (codeUrl) {
      var qrcode = new QRCode(document.getElementById('qrcode'), {
        text: codeUrl,
        top: 200,
        width: 300,
        height: 300,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      return qrcode
    },
    // 驱动下载
    deviceBinding1 () {
      console.log('设备绑定')
      this.modalDevice1 = true
    },
    // 设备绑定
    deviceBinding () {
      console.log('设备绑定')
      this.modalDevice = true
    },
    // 客服电话
    deviceBinding2 () {
      console.log('客服电话')
      this.modalDevice2 = true
    },
    saveDevice () {
      updateUserGPY({ device_code: this.highMeter1 }).then(res => {
        if (res.data.errcode === 0) {
          this.$Notice.success({ title: '设备绑定成功', desc: '设备绑定成功，请注销重新登录' })
        } else {
          this.$Notice.error({ title: '绑定失败', desc: res.data.errmsg })
        }
      })
      this.$store.state.user.highMeter = this.highMeter1
    },
    ...mapMutations([
      'setBreadCrumb',
      'setTagNavList',
      'addTag',
      'setLocal',
      'setFirstMenuId',
      'setHomeRoute',
      'closeTag'
    ]),
    ...mapActions([
      'handleLogin',
      'getUnreadMessageCount',
      'getAjaxRouterData'
    ]),
    turnToPage (route) {
      // console.log(route, 'main/turnToPage')
      let { name, params, query } = {}
      if (typeof route === 'string') name = route
      else {
        name = route.name
        params = route.params
        query = route.query
      }
      if (name.indexOf('isTurnByHref_') > -1) {
        window.open(name.split('_')[1])
        return
      }
      this.$router.push({
        name,
        params,
        query
      })
    },
    handleCollapsedChange (state) {
      this.collapsed = state
    },
    handleCloseTag (res, type, route) {
      if (type !== 'others') {
        if (type === 'all') {
          this.turnToPage(this.$config.homeName)
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route)
          }
        }
      }
      this.setTagNavList(res)
    },
    handleClick (item) {
      // console.log(item, '执行main/handleClick')
      this.turnToPage(item)
    },
    getRouterListData () {
      getRouterReq('222').then(res => {
        let listData = getMenuByRouter(res.data, 'admin')
        this.menuList001 = listData
      })
    },
    groupMenuSelect (id, menusData) {
      // this.setFirstMenuId(id)
      localSave('first-menus-data', JSON.stringify(menusData))
      this.$store.dispatch('getAjaxRouterData', id)
    },
    findHtmlList () {
      findHtmlList({}).then(res => {
        if (res.data.errcode === 0) {
          if (res.data.data) {
            this.htmllist = res.data.data
            this.opennoticeDocument()
          }
        }
      })
    },
    opennoticeDocument () {
      for (var i in this.htmllist) {
        let item = this.htmllist[i]
        if (item.isshow === '1') {
          this.display_model1_obj1.html = item.html
          this.display_model1_obj1.index_id = item.id
          this.display_model1_obj1.modal1 = true
          item.isshow = '0'
          this.countDown(item.showtime)
          return
        }
      }
    },
    showkefu () {
      getHtml1({}).then(res => {
        if (res.data.errcode === 0) {
          this.modalDevice2html = res.data.data.html
        }
      })
    },
    countDown (time) {
      this.time = time + 's'
      if (time === 0) {
        this.disabledCodeBtn = true
        this.time = ''
        return
      } else {
        this.disabledCodeBtn = false
        time--
      }
      setTimeout(() => {
        this.countDown(time)
      }, 1000)
    },
    savelogea () {
      let params = {
        index_id: this.display_model1_obj1.index_id
      }
      savelog(params).then(res => {})
      this.display_model1_obj1.modal1 = false
      setTimeout(() => {
        this.opennoticeDocument()
      }, 500)
    }
  },
  watch: {
    '$route' (newRoute) {
      console.log(newRoute, 'watch新的路由变化')
      // console.log(this.menuList, '获取当菜单数据')
      let tempMenuList = this.menuList
      for (let key in tempMenuList) {
        let childData = tempMenuList[key].children
        if (tempMenuList[key].name && tempMenuList[key].name === newRoute.name) {
          console.log('ok11')
          newRoute.meta.title = tempMenuList[key].meta.title // 为了不在路由里面取名字写的循环
        } else {
          if (tempMenuList[key].children && tempMenuList[key].children.length > 0) {
            for (let k2 in childData) {
              let chid = childData[k2]
              if (chid.name === newRoute.name) {
                console.log('ok')
                newRoute.meta.title = chid.meta.title // 为了不在路由里面取名字写的循环
              }
            }
          }
        }
      }
      const { name, query, params, meta } = newRoute
      if (newRoute.meta.hide === true) {
        this.addTag({
          route: { name, query, params, meta },
          type: 'push'
        })
        this.setBreadCrumb(newRoute)
        this.tempTagNavList = []
        for (var i = 0; i < this.tagNavList.length; i++) {
          if (this.tagNavList[i].meta.hide === true) {
            this.tempTagNavList.push(this.tagNavList[i])
          }
        }
        this.setTagNavList(getNewTagList(this.tempTagNavList, newRoute))
      }
    }
  },
  mounted () {
    this.startMove()
    this.location_url = window.location.href
    this.mzMenulist()
    this.setTagNavList()
    this.setHomeRoute(routers)
    const { name, params, query, meta } = this.$route
    this.addTag({
      route: { name, params, query, meta }
    })
    let severUserInfo = this.$store.state.user.severUserInfo
    this.loginCompanyType = severUserInfo.company_type
    this.device_code = severUserInfo.email
    this.company_codes = severUserInfo.company_code
    this.loginNames = severUserInfo.loginName
    this.personData.name = severUserInfo.name
    this.personData.company_name = severUserInfo.company_name
    this.highMeter1 = severUserInfo.email
    this.routeList = this.$store.state.app.mainv3Nav
    this.showkefu()
  }
}
</script>
